package com.shugl.demo.config.interceptor;

import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


/**
 * 拦截器
 * @author admin
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String uri = request.getRequestURI();

		String contentType = request.getHeader("content-type");
		String token = request.getHeader("token");

		log.info("拦截到请求：{}", uri);
		log.info("请求时间：{}", DateFormat.getDateTimeInstance().format(new Date()));
		log.info("token：" + (StringUtil.isEmpty(token) ? "无token" : token) + "");
		if (!(StringUtil.isNotEmpty(contentType) && contentType.contains("application/json"))) {
			log.info("请求参数:{}", getParamString(request.getParameterMap()));
		}
		log.trace(handler.toString());

		return true;
	}


	/**
	 * 解析参数(form-data)
	 *
	 * @param map
	 * @return
	 */
	private String getParamString(Map<String, String[]> map) {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String[]> e : map.entrySet()) {
			sb.append(e.getKey()).append("=");
			String[] value = e.getValue();
			if (value != null && value.length == 1) {
				sb.append(value[0]).append("\t");
			} else {
				sb.append(Arrays.toString(value)).append("\t");
			}
		}
		return sb.toString();
	}

//	private String getJsonParamString(HttpServletRequest request, HttpServletResponse response) {
//		return null;
//	}


}
